'use strict';
var enums = require('../shared/enums.js');

module.exports = function(sequelize, DataTypes) {
  var profile = sequelize.define('profile', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV1
    },
    userId: {
      type: DataTypes.STRING(24),
      allowNull: false,
    },
    mobile: {
      type: DataTypes.STRING(11),
      validate: {
        is: {
          args: /^1\d{10}$/ig,
          msg: '无效的手机号码'
        }
      }
    },
    nickname: DataTypes.STRING,
    avatar: DataTypes.STRING,
    birth: {
      type: DataTypes.DATE,
      allowNull: true
    },
    gender: {
      type: DataTypes.ENUM(enums.gender),
      allowNull: false,
      defaultValue: 'unknown',
      validate: {
        isIn: [enums.gender]
      }
    },
    defaultAddress: {
      type: DataTypes.UUID,
      validate: {
        isUUID: true
      }
    }
  }, {
    classMethods: {
      associate: function(models) {
        profile.hasOne(models.autonym);
        profile.hasMany(models.order, { as: 'owner', foreignKey: 'ownerId' });
        profile.hasMany(models.order, { as: 'postman', foreignKey: 'postmanId' });
        profile.belongsToMany(models.product, {
          through: models.cart
        });
      }
    },
    paranoid: true
  });
  return profile;
};
